/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package extension.tienlen.handler;

import com.smartfoxserver.v2.entities.User;
import com.smartfoxserver.v2.entities.data.ISFSObject;
import com.smartfoxserver.v2.extensions.BaseClientRequestHandler;
import extension.game.room.RoomExtension;
import extension.room.analyse.Card;
import extension.room.tienlen.TienlenFlag;
import extension.room.tienlen.TienlenGame;
import extension.room.tienlen.TienlenPlayer;
import extension.room.tienlen.TienlenResponse;
import java.util.List;
import log.Debug;

/**
 *
 * @author daz
 */
public class FightCardHandler extends BaseClientRequestHandler {

    @Override
    public void handleClientRequest(User user, ISFSObject params) {
        List<Integer> listCards = (List<Integer>) params.getIntArray(TienlenFlag.LIST_CARDS);
        RoomExtension tienlenExtension = (RoomExtension) getParentExtension();
        TienlenGame game = (TienlenGame) tienlenExtension.getGame();
        TienlenPlayer p = game.getPlayerFight();

        if (p.getName().equals(user.getName())
                && !listCards.isEmpty()) {
            if (game.checkCard(listCards)) {
                if (game.getIsChargePenalty()) {
                    game.updateMoneChange();
                }
                game.removeCardInHand(listCards);
                List<User> listSend = tienlenExtension.getParentRoom().getUserList();
                TienlenResponse response = (TienlenResponse) tienlenExtension.getResponse();
                response.sendFightCard(listCards, game.getGameTurn(), 1, listSend);
                logShowPhom(user.getName(), listCards);
                //check remain card
                if (p.getNumberCardInHands() <= 0) {
                    int rank = game.playerFinish();
                    response.sendFightAll(rank, p.getSeatPos(), game.getNumbeView());
                }

                if (!game.getIsFinishMatch()) {
                    game.nextTurn();
                } else {
                    game.onFinishMatch();
                }
            } else {
                TienlenResponse response = (TienlenResponse) tienlenExtension.getResponse();
                response.sendFightCard(0, user);
            }

            game.setIsChargePenalty(false);
        }
    }

    private void logShowPhom(String name, List<Integer> listPhom) {
        if (listPhom != null && !listPhom.isEmpty()) {
            StringBuilder builder = new StringBuilder();
            for (Integer card : listPhom) {
                builder.append(Card.getName(card));
                builder.append(",");
            }
            Debug.d(name + "-fight:" + builder.toString());
        }
    }
}
